package com.css.fxfzypg.modules.model.repository.Impl;

import com.css.fxfzypg.constants.YNEnum;
import com.css.fxfzypg.modules.model.entity.IntensityAttenuation;
import com.css.fxfzypg.modules.model.repository.IntensityAttenuationRepository;
import com.css.fxfzypg.modules.model.vo.IntensityAttenuationVO;
import com.css.fxfzypg.util.CreateGson;
import com.css.fxfzypg.util.PlatformObjectUtils;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.entity.SUser;
import com.css.fxfzypg.zcpt.sys.service.SUserService;
import com.css.fxfzypg.zcpt.sys.service.SysAreaService;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Dbj
 * @date 2022年10月05日  14:04
 */
@Repository
public class IntensityAttenuationRepositoryImpl implements IntensityAttenuationRepository {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Resource
    private SUserService sUserService;

    @Resource
    private SysAreaService areaService;

    @Override
    public Map<String, Object> findPage(IntensityAttenuationVO vo, int curPage, int pageSize) {
        StringBuilder sql = new StringBuilder("select * from intensity_attenuation ");
        StringBuilder whereSql = new StringBuilder(" where is_valid ='" + YNEnum.Y.toString() + "'");
        String orderSql = " order by is_default desc,province_code";
        StringBuilder countSql = new StringBuilder("select count(*) from intensity_attenuation ");
        StringBuilder str = new StringBuilder("");
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(PlatformSessionContext.getUserID());
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        if (!vo.getNation()) {
            whereSql.append(" and (org_name = '系统默认' or province='").append(sUser.getProvinceId()).append("')");
        }
        if (!PlatformObjectUtils.isEmpty(vo.getModelName())) {
            whereSql.append(" and model_name like '%" + vo.getModelName() + "%'");
        }
        if (!PlatformObjectUtils.isEmpty(vo.getProvince())) {
            if ("cd726776c7de41e4a41dcdb3d90b2806".equals(vo.getProvince()) || "225ac763ab714524b87d95140a93a4a5".equals(vo.getProvince()) || "8a3f7d3f78ad456f92f487a979091c7f".equals(vo.getProvince()) || "afcbf07008a34c2e85917cfd34008033".equals(vo.getProvince())) {
                //拿到北京上海天津重庆四省的省id
                String pid = areaService.getParentId(vo.getProvince());
                vo.setProvince(pid);
            }
            whereSql.append(" and province='").append(vo.getProvince()).append("'");
        }
        if (!PlatformObjectUtils.isEmpty(vo.getCity())) {
            whereSql.append(" and (position('").append(vo.getCity()).append("' in city) > 0 ");
            whereSql.append(" or city='全部')");
        }
        String limitSql = " limit " + pageSize + " offset " + (curPage - 1) * pageSize;
        String sqlWhole = sql.append(whereSql).append(orderSql).append(limitSql).toString();
        countSql.append(whereSql);
        List<IntensityAttenuation> list = jdbcTemplate.query(sqlWhole, new BeanPropertyRowMapper<>(IntensityAttenuation.class));
        Integer total = jdbcTemplate.queryForObject(countSql.toString(), Integer.class);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("total", total);
        map.put("rows", list);
        return map;
    }

    @Override
    public Map<String, Object> findPageForXczh(IntensityAttenuationVO vo, int curPage, int pageSize) {
        StringBuilder sql = new StringBuilder("select * from intensity_attenuation ");
        StringBuilder whereSql = new StringBuilder(" where is_valid ='" + YNEnum.Y.toString() + "'");
        String orderSql = " order by is_default desc,province_code";
        StringBuilder countSql = new StringBuilder("select count(*) from intensity_attenuation ");
        if (!PlatformObjectUtils.isEmpty(vo.getModelName())) {
            whereSql.append(" and model_name like '%" + vo.getModelName() + "%'");
        }
        if (!PlatformObjectUtils.isEmpty(vo.getProvince())) {
            if ("cd726776c7de41e4a41dcdb3d90b2806".equals(vo.getProvince()) || "225ac763ab714524b87d95140a93a4a5".equals(vo.getProvince()) || "8a3f7d3f78ad456f92f487a979091c7f".equals(vo.getProvince()) || "afcbf07008a34c2e85917cfd34008033".equals(vo.getProvince())) {
                //拿到北京上海天津重庆四省的省id
                String pid = areaService.getParentId(vo.getProvince());
                vo.setProvince(pid);
            }
            whereSql.append(" and (org_name = '系统默认' or province='").append(vo.getProvince()).append("')");
        }
        if (!PlatformObjectUtils.isEmpty(vo.getCity())) {
            whereSql.append(" and (position('").append(vo.getCity()).append("' in city) > 0 ");
            whereSql.append(" or city='全部')");
        }
        String limitSql = " limit " + pageSize + " offset " + (curPage - 1) * pageSize;
        String sqlWhole = sql.append(whereSql).append(orderSql).append(limitSql).toString();
        countSql.append(whereSql);
        List<IntensityAttenuation> list = jdbcTemplate.query(sqlWhole, new BeanPropertyRowMapper<>(IntensityAttenuation.class));
        Integer total = jdbcTemplate.queryForObject(countSql.toString(), Integer.class);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("total", total);
        map.put("rows", list);
        return map;
    }

    @Override
    public IntensityAttenuation getModelById(String id) {
        String sql = "select * from intensity_attenuation where is_valid ='" + YNEnum.Y.toString() + "' and id='" + id + "'";
        List<IntensityAttenuation> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(IntensityAttenuation.class));
        return PlatformObjectUtils.isNotEmpty(query)?query.get(0):null;
    }

    @Override
    public IntensityAttenuation getDefaultModel() {
        String sql = "select * from intensity_attenuation where is_valid ='" + YNEnum.Y.toString() +
                "' and is_default='" + YNEnum.Y.toString() + "' limit 1";
        return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(IntensityAttenuation.class));
    }

    @Override
    public IntensityAttenuation getDefaultModelByModelName(String modelName) {
        String sql = "select * from intensity_attenuation where is_valid ='" + YNEnum.Y.toString() +
                "' and is_default='" + YNEnum.Y.toString() + "' and model_name='" + modelName + "' limit 1";
        return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(IntensityAttenuation.class));
    }

    @Override
    public List<IntensityAttenuation> getByDivision(String province, String city, int isNa) {
        String sql = "select * from intensity_attenuation where is_valid ='" + YNEnum.Y.toString() + "' and province='" + province + "'";
        if (PlatformObjectUtils.isNotEmpty(city)) {
            sql = sql + " and city='" + city + "'";
        }
        sql = sql + " order by create_time desc ";
        if (isNa == 0) {
            sql = sql + " limit 1 ";
        }
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(IntensityAttenuation.class));
    }

    @Override
    public void save(IntensityAttenuation intensity) throws ParseException {
        jdbcTemplate.update("insert into intensity_attenuation(id,model_name,long_ratio1,long_ratio2,long_ratio3,long_ratio4,long_symbol,short_ratio1,short_ratio2,short_ratio3,short_ratio4,short_symbol," +
                        "formula_ratio1,formula_ratio2,scale,is_default,province,city,create_user_id,create_user_name,create_time,org_id,org_name,is_valid,province_code,type) " +
                        "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                intensity.getId(), intensity.getModelName(), intensity.getLongRatio1(), intensity.getLongRatio2(), intensity.getLongRatio3(), intensity.getLongRatio4(), intensity.getLongSymbol(),
                intensity.getShortRatio1(), intensity.getShortRatio2(), intensity.getShortRatio3(), intensity.getShortRatio4(), intensity.getShortSymbol(),
                intensity.getFormulaRatio1(), intensity.getFormulaRatio2(), intensity.getScale(), intensity.getIsDefault(), intensity.getProvince(),
                intensity.getCity(), intensity.getCreateUserId(), intensity.getCreateUserName(), intensity.getCreateTime(),
                intensity.getOrgId(), intensity.getOrgName(), intensity.getIsValid(), intensity.getProvinceCode(), intensity.getType());
    }

    @Override
    public void update(IntensityAttenuation intensity) {
        StringBuilder sql = new StringBuilder("update intensity_attenuation set ");
        sql.append("model_name='").append(intensity.getModelName()).append("',");
        sql.append("long_ratio1=").append(intensity.getLongRatio1()).append(",");
        sql.append("long_ratio2=").append(intensity.getLongRatio2()).append(",");
        sql.append("long_ratio3=").append(intensity.getLongRatio3()).append(",");
        sql.append("long_ratio4=").append(intensity.getLongRatio4()).append(",");
        sql.append("long_symbol='").append(intensity.getLongSymbol()).append("',");
        sql.append("short_ratio1=").append(intensity.getShortRatio1()).append(",");
        sql.append("short_ratio2=").append(intensity.getShortRatio2()).append(",");
        sql.append("short_ratio3=").append(intensity.getShortRatio3()).append(",");
        sql.append("short_ratio4=").append(intensity.getShortRatio4()).append(",");
        sql.append("short_symbol='").append(intensity.getShortSymbol()).append("',");
        if (intensity.getFormulaRatio1() != null) {
            sql.append("formula_ratio1=").append(intensity.getFormulaRatio1()).append(",");
        }
        if (intensity.getFormulaRatio2() != null) {
            sql.append("formula_ratio2=").append(intensity.getFormulaRatio2()).append(",");
        }
        if (intensity.getScale() != null) {
            sql.append("scale=").append(intensity.getScale()).append(",");
        }
        sql.append("update_user_id='").append(intensity.getUpdateUserId()).append("',");
        //Timestamp time = new Timestamp(System.currentTimeMillis());
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(date);
        sql.append("update_time='").append(format).append("'");
        sql.append(" where id='").append(intensity.getId()).append("'");
        jdbcTemplate.update(sql.toString());
//        jdbcTemplate.update("update intensity_attenuation set model_name=?,long_ratio1=?,long_ratio2=?,long_ratio3=?,long_ratio4=?,long_symbol=?,short_ratio1=?,short_ratio2=?,short_ratio3=?,short_ratio4=?,short_symbol=?,formula_ratio1=?,formula_ratio2=?,scale=?," +
//                        "update_user_id=?,update_time=? where id=?",intensity.getModelName(),intensity.getLongRatio1(),intensity.getLongRatio2(),intensity.getLongRatio3(),intensity.getLongRatio4(),intensity.getLongSymbol(),
//                intensity.getShortRatio1(),intensity.getShortRatio2(),intensity.getShortRatio3(),intensity.getShortRatio4(),intensity.getShortSymbol(),
//                intensity.getFormulaRatio1(),intensity.getFormulaRatio2(),intensity.getScale(),intensity.getUpdateUserId(),intensity.getUpdateTime(),intensity.getId());
    }


    @Override
    public void delete(String userId, Date updateTime, String id) {
        jdbcTemplate.update("update intensity_attenuation set is_valid=?,update_user_id=?,update_time=? where id=?", YNEnum.N.toString(), userId, updateTime, id);
    }

    @Override
    public Integer countByProvince(String province) {
        return jdbcTemplate.queryForObject("SELECT count(*) from intensity_attenuation where province = '" + province + "'  and is_valid ='1' ", Integer.class);
    }

    @Override
    public Integer countByYearPrefixLike(String taskYear, String provinceId) {
        return jdbcTemplate.queryForObject("SELECT count(*) FROM intensity_attenuation where (TO_CHAR(create_time, 'yyyy-MM-dd hh24:mi:ss') LIKE '" + taskYear + "%' or TO_CHAR(update_time, 'yyyy-MM-dd hh24:mi:ss') LIKE '" + taskYear + "%') and province = '" + provinceId + "' and is_valid ='1' ", Integer.class);
    }
}
